package com.dek.seckill.common.redis;


import com.dek.seckill.common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisService {

    @Autowired
    JedisPool jedisPool;

    @Autowired
    RedisConfig redisConfig;

    /**
     * 获取单个对象
     * @param keyPrefix
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(KeyPrefix keyPrefix, String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = keyPrefix.getPrefix() + key;
            return JsonUtil.fromJson(jedis.get(realKey), clazz);
        } finally {
            return2Pool(jedis);
        }
    }

    /**
     * 设置对象
     * @param keyPrefix
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public <T> boolean set(KeyPrefix keyPrefix,String key, T value) {
        Jedis jedis = null;
        try {
            String realKey = keyPrefix.getPrefix() + key;
            jedis = jedisPool.getResource();
            int expireSeconds = keyPrefix.expireSeconds();
            if (expireSeconds > 0) {
                System.out.println(expireSeconds);
                jedis.setex(realKey, expireSeconds, JsonUtil.toJson(value));
            } else {
                jedis.set(realKey, JsonUtil.toJson(value));
            }
            return true;
        } finally {
            return2Pool(jedis);
        }
    }

    /**
     * 判断是否存在
     * @param keyPrefix
     * @param key
     * @param <T>
     * @return
     */
    public <T> boolean exists(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.exists(realKey);
        } finally {
            return2Pool(jedis);
        }
    }

    /**
     * 增加值
     * @param keyPrefix
     * @param key
     * @return
     */
    public Long incr(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.incr(realKey);
        } finally {
            return2Pool(jedis);
        }
    }

    /**
     * 减少值
     * @param keyPrefix
     * @param key
     * @return
     */
    public Long decr(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.decr(realKey);
        } finally {
            return2Pool(jedis);
        }
    }

    /**
     * 关闭连接
     * @param jedis
     */
    private void return2Pool(Jedis jedis) {
        if (jedis != null)
            jedis.close();
    }
}
